package com.idna.wsconsumer.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.xml.namespace.QName;

import org.apache.axis2.databinding.utils.BeanUtil;

import org.apache.axiom.om.*;

/**
 * @author kan.sun
 *
 */
public class ClientUtilImpl implements ClientUtil
{
	private static ApplicationUtilImpl utils;
	private static Properties prop;
	private static String xmlRequest;

	private void init(String preffix)
	{
		try
		{
			utils = new ApplicationUtilImpl();
			prop = utils.loadProperty(ApplicationUtilImpl.PROP_PATH);
			xmlRequest = utils.readFile(prop.getProperty(preffix.trim().toLowerCase()+"_xmlrequest"));
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	
	/* (non-Javadoc)
	 * @see net.icdpublishing.wsconsumer.utils.ClientUtil#getOperationOMElement(java.lang.String, java.lang.String)
	 */
	public OMElement getOperationOMElement(String operationName, String rootElement)
	{
		init(rootElement);

		//More powerful BeanUtil
		OMElement elem = BeanUtil.getOMElement
		(
				new QName(operationName), 
				new String[]{xmlRequest, "1"}, 
				null, false, null
		);
		
		return elem;
		
		/*OMFactory fac = OMAbstractFactory.getOMFactory();
		
		OMElement operation = fac.createOMElement(operationName, null);
		
			//Compose the request parameters for search operation
			OMElement message = fac.createOMElement("searchRequest", null);
				//Parameter 1: searchPacket containing a string read from xml input
				OMElement part1 = fac.createOMElement("searchPacket", null);
				//part1.addAttribute(inputType);
				part1.addChild(fac.createOMText(xmlRequest));
				
				//Parameter 2: apiVersion with the default value 1
				OMElement part2 = fac.createOMElement("apiVersion", null);
				//part2.addAttribute(inputType);
				part2.addChild(fac.createOMText("1"));
			message.addChild(part1);
			message.addChild(part2);
		//Bind inputs with the operation
		operation.addChild(part1);
		operation.addChild(part2);
				
		return operation;*/
		
	}
	
	public OMElement[] getPartOMElmenent(String[] localNames, String rootElement)
	{
		init(rootElement);
		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMElement[] parts = new OMElement[localNames.length];
		for(int i=0; i<localNames.length; i++)
		{
			OMElement part = fac.createOMElement(localNames[i], null);
			if(part.getQName().getLocalPart().equalsIgnoreCase("searchPacket"))
			{
				part.addChild(fac.createOMText(xmlRequest));
			}
			else if(part.getQName().getLocalPart().equalsIgnoreCase("apiVersion"))
			{
				part.addChild(fac.createOMText("1"));
			}
			parts[i] = part;
		}
		return parts;
	}
}
